'use client';

import { useState, useEffect } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import ImageViewer2D from '../../../components/ImageViewer2D';
import ImageViewer3D from '../../../components/ImageViewer3D';
import TaskParameterConfig from '../../../components/TaskParameterConfig';
import TaskResultDisplay from '../../../components/TaskResultDisplay';

import { fetchDatasetDetail, getImageUrl, runTaskAPI, getMaskUrl } from '@/lib/api';

export default function OperationPage() {
  const [selectedImage, setSelectedImage] = useState(null);
  const [taskStatus, setTaskStatus] = useState('idle');
  const [taskResult, setTaskResult] = useState(null);
  const [images, setImages] = useState([]);
  const [datasetType, setDatasetType] = useState('2d'); // 默认2D
  const [useTestImage, setUseTestImage] = useState(false); // 是否使用测试图像
  const [maskUrls, setMaskUrls] = useState([]); // 存储mask信息，包含url, opacity, colorMap
  const params = useParams();
  const searchParams = useSearchParams();
  const datasetId = params.datasetId;
  const taskId = params.taskId;
  const clinicalscene = searchParams.get('clinicalscene');

  // 根据数据集类型确定使用哪种查看器
  const shouldUse2DViewer = datasetType === '2d';

  // 首次加载，当数据集ID变化时，获取数据集详情和图像列表
  useEffect(() => {
    async function loadImages() {
      try {
        const detail = await fetchDatasetDetail(datasetId);
        if (detail && Array.isArray(detail.images)) {
          // 只暴露 id 和 filename，不暴露 path
          setImages(detail.images.map(img => ({
            id: img.id,
            name: img.filename,
            url: getImageUrl(datasetId, img.id)  // 使用API函数构建URL
          })));

          // 设置数据集类型
          if (detail.type) {
            setDatasetType(detail.type);
          }
        }
      } catch (error) {
        setImages([]);
      }
    }
    loadImages();
  }, [datasetId]);

  // 测试图像URL
  // 1. 测试地址池
  const TEST_URL_MAP = {
    '2d': 'http://10.69.64.129:8000/data/chest-xray/1-s2.0-S0929664620300449-gr2_lrg-a.jpg',
    '3d': 'http://10.69.64.129:8000/data/liver/source_axial_LR.nii.gz',
  };

  // 2. 选择一个数据
  // 选择图像时根据 useTestImage 决定使用测试地址还是正常地址
  const handleImageSelect = (image) => {
    if (useTestImage) {
      // 根据数据集类型自动选择 2D 或 3D 测试地址
      const testUrl = TEST_URL_MAP[datasetType.toLowerCase()] || TEST_URL_MAP['2d']; // 默认回退到 2D
      setSelectedImage({
        id: 'test-image',
        name: '测试图像',
        url: testUrl,
      });
    } else {
      // 正常逻辑
      setSelectedImage({
        ...image,
        url: getImageUrl(datasetId, image.id),
      });
    }
  };

  // 启动真实任务
  const handleTask = async (parameters) => {
    if (!selectedImage) return;

    setTaskStatus('running');

    // 直接使用 taskId，不再依赖 classificationSubType
    const actualTaskId = taskId;

    // 调用后端API执行任务
    const result = await runTaskAPI(
      clinicalscene,
      actualTaskId,
      parameters,
      selectedImage.url,
    );
    // 设置最后的执行结果
    setTaskResult(result);

    // 如果是分割任务，提取mask URLs
    if (taskId === 'segmentation' && result.results?.segmentations) {
      // 对于分割任务，仅设置URL，保持默认的opacity和colorMap
      const masks = result.results.segmentations.map(seg => ({
        url: getMaskUrl(seg.mask),
        opacity: 0.7,
        colorMap: 'red'
      }));
      setMaskUrls(masks);
    }

    setTaskStatus('completed');
  };

  // 根据任务类型渲染不同的图像查看器
  const renderImageViewer = () => {
    if (!selectedImage) {
      return (
        <div className="bg-white border border-gray-200 rounded-lg p-8">
          <div className="text-center">
            <div className="text-6xl mb-4">🖼️</div>
            <h3 className="text-lg font-semibold text-gray-900 mb-2">请选择图像</h3>
            <p className="text-gray-600">从左侧列表中选择一张图像开始分析</p>
          </div>
        </div>
      );
    }

    // 根据 datasetType 判断使用哪种查看器
    if (shouldUse2DViewer) {
      return (
        <ImageViewer2D
          imageUrl={selectedImage.url}
          imageName={selectedImage.name}
          detections={taskResult?.detections}
        />
      );
    } else {
      return (
        <ImageViewer3D
          imageUrl={selectedImage.url}
          imageName={selectedImage.name}
          maskUrls={maskUrls}
        />
      );
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8">
        <header className="mb-8">
          <nav className="text-sm text-gray-600 mb-4">
            <Link href="/" className="hover:text-blue-600">首页</Link>
            {' > '}
            <Link href={`/dataset?clinicalscene=${clinicalscene}`} className="hover:text-blue-600">数据集与任务选择</Link>
            {' > '} 操作界面
          </nav>
          <h1 className="text-2xl font-bold text-gray-900">医学影像分析</h1>
          <div className="flex justify-between items-center mt-2">
            <p className="text-gray-600">
              数据集: {datasetId} | 任务: {taskId} | 类型: {datasetType === '2d' ? '2D医学影像' : '3D医学影像'} | 模式: {shouldUse2DViewer ? '2D查看' : '3D查看'}
            </p>
            <button
              onClick={() => setUseTestImage(!useTestImage)}
              className={`px-3 py-1 text-sm rounded ${useTestImage ? 'bg-green-500 text-white' : 'bg-gray-200 text-gray-700'}`}
            >
              {useTestImage ? '测试模式开启' : '测试模式关闭'}
            </button>
          </div>
        </header>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 左侧：数据选择和参数配置 */}
          <div className="lg:col-span-1 space-y-6">
            {/* 数据列表 */}
            <div>
              <h3 className="text-lg font-semibold mb-4">选择数据</h3>
              <div className="max-h-64 overflow-y-auto border border-gray-200 rounded-lg">
                {images.map((image) => (
                  <div
                    key={image.id}
                    onClick={() => handleImageSelect(image)}
                    className={`p-3 cursor-pointer border-b border-gray-100 hover:bg-gray-50 ${selectedImage?.id === image.id ? 'bg-blue-50 border-blue-200' : ''
                      }`}
                  >
                    <div className="font-medium text-sm">{image.name}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* 参数配置 */}
            <TaskParameterConfig
              taskId={taskId}
              onStartTask={handleTask}
              disabled={!selectedImage || taskStatus === 'running'}
              taskStatus={taskStatus}
            />
          </div>

          {/* 右侧：图像显示和结果 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 图像查看器 - 根据taskType动态选择 */}
            <div>
              {renderImageViewer()}
            </div>

            {/* 结果显示 */}
            {taskResult && (
              <TaskResultDisplay
                result={taskResult}
                taskId={taskId}
                imageUrl={selectedImage?.url}
                onShowMask={(imageUrl, maskUrl, opacity = 0.7, colorMap = 'red') => {
                  // 当点击显示结果时，更新mask URLs
                  if (maskUrl === null || maskUrl === undefined) {
                    // 隐藏所有 mask
                    setMaskUrls([]);
                  } else {
                    // 显示指定的 mask，并包含opacity和colorMap信息
                    setMaskUrls([{
                      url: maskUrl,
                      opacity: opacity,
                      colorMap: colorMap
                    }]);
                  }
                }}
              />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}